using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

// 挂载到格子预制体上
namespace FrameWork.Inventory
{
    public class Slot : MonoBehaviour,IDragHandler,IEndDragHandler,IBeginDragHandler
    {
        [SerializeField] private Button button;
        
        [SerializeField] private RectTransform rectTransform;
        [SerializeField] private CanvasGroup canvasGroup;
        private Vector2 startPosition;
        // 物品图片
        public Image itemImage;
        // 数量
        public TMP_Text itemCount;
        
        [SerializeField] private string itemName;
        
        //
        public InventoryItem GetItem { get; private set; }

        private void Start()
        {
            rectTransform = GetComponent<RectTransform>();
            canvasGroup = GetComponent<CanvasGroup>();
            button = GetComponent<Button>();
            button.onClick.AddListener(OnClick);
        }

        private void OnClick()
        {
            if(InventoryDescription.Instance != null)
                InventoryDescription.Instance.SetDescription(GetItem.item.ItemName, GetItem.item.ItemDescription);
            if(ShopDescription.Instance != null)
                ShopDescription.Instance.SetDescription(GetItem.item);
            // print(GetItem.item.ItemName);
        }
        
        public void SetSlot(InventoryItem inventoryItem)
        {
            GetItem = inventoryItem;
            itemName = inventoryItem.item.ItemName;
            itemImage.gameObject.SetActive(true);
            itemImage.sprite = inventoryItem.item.ItemIcon;
            itemCount.text = inventoryItem.quantity.ToString();
        }

        public void ResetSlot()
        {
            itemImage.gameObject.SetActive(false);
            itemImage.sprite = null;
            itemCount.text = "";
        }

        // 开始拖拽
        public void OnBeginDrag(PointerEventData eventData)
        {
            startPosition = rectTransform.anchoredPosition; // 保存移动前的位置
            canvasGroup.blocksRaycasts = false;
            canvasGroup.alpha = 0.5f;
        }

        // 正在拖拽
        public void OnDrag(PointerEventData eventData)
        {
            rectTransform.anchoredPosition += eventData.delta;
        }

        // 结束拖拽
        public void OnEndDrag(PointerEventData eventData)
        {
            rectTransform.anchoredPosition = startPosition; // 恢复到初始位置
            canvasGroup.blocksRaycasts = true;
            canvasGroup.alpha = 1f;
        }
    }
}
